package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Resource
    CategoryDao categoryDao;

    @Resource
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //查询所有的菜单，包含父子关系的，通过Tree展示
    @Override
    public List<CategoryEntity> listWithTree() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        //1、查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(wrapper);
        //2、组装成父子的树形结构
        //2.1找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
            //菜单的排序
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu1.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    //1、检查当前删除的菜单，是否被别的地方引用
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //1、检查当前菜单被什么地方引用了
        //TODO
        baseMapper.deleteBatchIds(asList);
    }

    //获取三级联动时的路径，回显对应的名称，通过catelogId查询
    //[2,22,222]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> path = findParentPath(catelogId, paths);
        Collections.reverse(path);
        return path.toArray(new Long[path.size()]);
    }

    //级联更新所有的关联数据
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
            //同步更新其他关联表中的数据
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

            //TODO 更新其他关联
    }

    //递归查询三级联动的路径
    //[222,22,2]
    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1、收集当前节点
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     * //递归查询一级分类下的所有子分类  ,从所有的分类菜单中查询
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map((categoryEntity) -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //进行sort排序的空指针异常过滤
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu1.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}